import {
  Component,
  OnInit,
  ViewChild,
  TemplateRef,
  ChangeDetectorRef,
} from '@angular/core';
import {
  NzMessageService,
  NzModalService,
  UploadXHRArgs,
  UploadFile,
} from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { STComponent, STColumn, STData, STChange } from '@delon/abc';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {
  HttpRequest,
  HttpEvent,
  HttpClient,
  HttpEventType,
  HttpResponse,
} from '@angular/common/http';
import { IntegralService } from '../integral.service';

@Component({
  selector: 'listpanel',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
})
export class ListComponent implements OnInit {
  fileList = [];
  previewImage = '';
  previewVisible = false;
  downloadPath = '';
  categoryList = [];

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };

  customReq = (item: UploadXHRArgs) => {
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress: true,
      withCredentials: true,
    });

    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this._http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total) * 100;
          }
          // 处理上传进度条，必须指定 `percent` 属性来表示进度
          item.onProgress(event, item.file);
        } else if (event instanceof HttpResponse) {
          // 处理成功
          item.onSuccess(event.body, item.file, event);
          let obj = event.body as any;
          this.downloadPath = obj.downloadPath;
        }
      },
      err => {
        // 处理失败
        item.onError(err, item.file);
      },
    );
  };

  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 6,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 97, text: '异常', value: false, type: 'error', checked: false },
  ];
  @ViewChild('st')
  st: STComponent;
  columns: STColumn[] = [
    { title: '序号', index: '_index' },
    { title: 'ID', index: 'integralId' },
    { title: '头像', index: 'headImgUrl', type: 'img' },
    { title: '昵称', index: 'nickname' },
    { title: '姓名', index: 'userName' },
    { title: '电话', index: 'phone' },
    { title: '积分', index: 'integral' },
    { title: '创建时间', index: 'tradeTime', type: 'date' },
    // { title: '更新时间', index: 'updateTime', type: 'date' },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          click: (item: any) => this.edit(this.modalContent, item),
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  columns4Standard: STColumn[] = [];

  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private integralService: IntegralService,
    private modalService: NzModalService,
    private fb: FormBuilder,
    private _http: HttpClient,
  ) {}

  @ViewChild('modalContent')
  modalContent: TemplateRef<{}>;

  shopImg: null;
  qrCodeImg: null;

  edit(tpl: TemplateRef<{}>, item: any): any {
    // this.form.reset();
    this.form.patchValue({
      id: item.id,
      phone: item.phone,
      integral: item.integral,
    });

    this.headImgUrl = item.headImgUrl;

    this.modalSrv.create({
      nzWidth: 640,
      nzTitle: '会员详情',
      nzContent: tpl,
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        this.submitting = true;
        this.integralService.recharge([this.form.value]).subscribe(
          res => {
            this.submitting = false;
            if (res.success) {
              this.msg.success(`操作成功`);
              this.getData();
            }
          },
          err => {
            this.submitting = false;
            this.msg.error(`操作失败`);
          },
        );

        return false;
      },
    });
  }

  form: FormGroup;
  submitting = false;
  headImgUrl = null;

  ngOnInit() {
    this.form = this.fb.group({
      nickname: [null],
      realName: [null],
      phone: [null],
      integral: [null, [Validators.required]],
    });

    this.getData();
  }

  submit() {
    this.submitting = true;
    setTimeout(() => {
      this.submitting = false;
      this.msg.success(`提交成功`);
      this.cdr.detectChanges();
    }, 1000);
  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);

    if (this.q.status !== null && this.q.status > -1)
      this.q.statusList.push(this.q.status);

    this.loading = false;

    let tmp = [];
    let count = 0;
    this.integralService.queryList(null).subscribe(resp => {
      if (resp.success) {
        resp.data.list.forEach(element => {
          tmp.push(element);
          element._index = ++count;
        });

        this.data = tmp;
      }
    });
  }

  stChange(e: STChange) {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        this.totalCallNo = this.selectedRows.reduce(
          (total, cv) => total + cv.callNo,
          0,
        );
        this.cdr.detectChanges();
        break;
      case 'filter':
        this.getData();
        break;
    }
  }

  remove() {
    this.http
      .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
      .subscribe(() => {
        this.getData();
        this.st.clearCheck();
      });
  }

  approval() {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  add(tpl: TemplateRef<{}>) {
    this.form.reset();
    this.modalSrv.create({
      nzWidth: 640,
      nzTitle: '会员详情',
      nzContent: tpl,
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        this.submitting = true;
        this.integralService.recharge([this.form.value]).subscribe(
          res => {
            this.submitting = false;
            if (res.success) {
              this.msg.success(`操作成功`);
              this.getData();
            }
          },
          err => {
            this.submitting = false;
            this.msg.error(`操作失败`);
          },
        );

        return false;
      },
    });
    
  }

  reset() {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }
}
